const app = getApp();
let rtcroom = require('../../utils/rtcroom.js');

Page({
  /**
     * 页面的初始数据
     */
  data: {
    roomID: '', // 房间id
    roomname: '', // 房间名称
    beauty: 0,
    muted: false,
    debug: false,
    inputMsg: '',     // input信息
    comment: [],      // 评论区信息
    frontCamera: true,
    navStatusHeight: wx.getSystemInfoSync().statusBarHeight
  },

  onRoomEvent: function (e) {

    switch (e.detail.tag) {
      case 'recvTextMsg':
        {
        /**
             * res:
             * {
             *   roomID: roomInfo.roomID,
             *   userID: msg.fromAccountNick,
             *   nickName: msg.nickName,
             *   headPic: msg.headPic,
             *   textMsg: msg.content,
             *   time: msg.time
	         * }
             */
        console.log('收到消息:', e.detail.detail);
        let msg = JSON.parse(e.detail.detail);
        this.data.comment.push({
          content: msg.textMsg,
          name: msg.nickName,
          time: msg.time,
        });
        this.setData({
          comment: this.data.comment,
          toview: '',
        });
        // 滚动条置底
        this.setData({
          toview: 'scroll-bottom',
        });
        break;
      }
      case 'roomClosed':
        {
        /**
         * 房间关闭时会收到此通知，客户可以提示用户房间已经关闭，做清理操作
          */
        // 在房间内部才显示提示
        const detail = e.detail.detail;
        console.log('roomClose:', detail);
        this.closeRoom(detail.memberCount, detail.isTimeout);
        break;
      }
      case 'error':
        {
        // 在房间内部才显示提示
        console.error('error:', e.detail.detail);
        let pages = getCurrentPages();
        if (pages.length > 1 && (pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/tourist-room/tourist-room')) {
          wx.showModal({
            title: '提示',
            content: e.detail.detail,
            showCancel: false,
            complete: function () {
              pages = getCurrentPages();
              // 点击 modal 后，判断页面是否已跳转，防止跳转两次
              if (pages.length > 1 && (pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/tourist-room/tourist-room')) {
                  wx.navigateBack({
                  delta: 1,
                  });
              }
            },
          });
        }
        break;
      }
    }
  },

  closeRoom: function (memberCount, isTimeout) {
    const op = isTimeout ? 'alarmInvaild' : (memberCount > 1 ? 'alarmResolve' : 'alarmProvent');
    app.util.request({
      url: 'entry/wxapp/alarm',
      data: {
        op,
        roomid: this.data.roomID,
      },
      module: 'cm_video_alarm',
      complete: function (res) {
        const pages = getCurrentPages();
        if (pages.length > 1 && pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/tourist-room/tourist-room') {
          wx.navigateBack({
            delta: 1,
          });
        }
      },
    });
  },

  changeCamera: function () {
    let rtcroomCom = this.selectComponent('#rtcroom');
    if (rtcroomCom) {
      rtcroomCom.switchCamera();
    }
    this.setData({
      frontCamera: !this.data.frontCamera,
    });
  },
  setBeauty: function () {
    let beauty = (this.data.beauty == 0 ? 5 : 0);
    this.setData({
      beauty: beauty,
    });
  },
  changeMute: function () {
    this.data.muted = !this.data.muted;
    this.setData({
      muted: this.data.muted,
    });
  },
  checkDebug() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'checkSwitch',
      },
      module: 'cm_video_alarm',
      success: res => {
        if (res.data && res.data.errno == 0) {
          const data = res.data.data;
          if (data) {
            this.setData({ debug: data.is_debug == 1 });
          }
        }
      },
    });
  },
  showLog: function () {
    this.data.debug = !this.data.debug;
    this.setData({
      debug: this.data.debug,
    });
  },

  bindInputMsg: function (e) {
    this.data.inputMsg = e.detail.value;
  },

  sendComment: function(msg) {
    let rtcroomCom = this.selectComponent('#rtcroom');
    if (rtcroomCom) {
      if (this.data.inputMsg && this.data.inputMsg == '?info') {
        // 打印userID和RoomID到聊天窗口
        let time = new Date();
        let h = String(time.getHours());
        let m = String(time.getMinutes());
        let s = String(time.getSeconds());
        h.length == 1 ? (h = '0' + h) : '';
        m.length == 1 ? (m = '0' + m) : '';
        s.length == 1 ? (s = '0' + s) : '';
        time = h + ':' + m + ':' + s;
        let roomInfo = rtcroomCom.getRoomInfo();
        let accountInfo = rtcroomCom.getAccountInfo();
        this.data.comment.push({
          content: '您当前使用的userID为' + accountInfo.userID + ', roomID为' + roomInfo.roomID,
          name: '【本地消息】',
          time: time,
        });
        this.setData({
          comment: this.data.comment,
          toview: '',
        });
        this.setData({
          inputMsg: '',
        });
      } else {
        // 发送消息
        rtcroomCom.sendTextMsg(this.data.inputMsg);
        this.setData({
          inputMsg: '',
        });
      }
    }
  },

  /**
     * 生命周期函数--监听页面加载
     */
  onLoad: function (options) {
    console.log('room.js onLoad');
    let getLocation = () => {
      return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'gcj02',
          success: res => {
            console.log('获取地理位置成功', res);
            resolve({
              lat: res.latitude,
              lng: res.longitude,
            });
      },
          fail: res => {
            console.log('获取地理位置失败', res);
            resolve({
              lat: '',
              lng: '',
    });
          },
        });
      });
    };

    getLocation().then(locationInfo => {
      let {
        lat = '', lng = '',
      } = locationInfo;
        app.util.request({
          url: 'entry/wxapp/alarm',
          data: {
            op: 'alarmStart',
          lat,
          lng,
            userid: rtcroom.getAccountInfo().userID,
          },
          module: 'cm_video_alarm',
          success: res => {
            if (res.data && res.data.data) {
              let time = new Date();
              time = time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds();
              console.log('*************开始多人音视频：' + time + '**************');
            console.log('*************发送地理位置：', lat, lng, '**************');
              const roomID = res.data.data.roomid;
              this.data.role = options.type;
              this.data.roomname = options.roomName;
              this.data.username = options.userName;

              this.setData({
                roomID,
                roomname: this.data.roomname,
                username: this.data.username,
              }, function() {
                let rtcroomCom = this.selectComponent('#rtcroom');
                if (rtcroomCom) {
                  rtcroomCom.start().then(roomid => {
                    app.util.request({
                      url: 'entry/wxapp/alarm',
                      data: {
                        op: 'postUserId',
                        roomid,
                        user_id: rtcroom.getAccountInfo().userID,
                      },
                      module: 'cm_video_alarm',
                    });
                  });
                }
                if (this.data.initCallback) {
                  this.data.initCallback();
                }
              });
            }
      },
    });
    });
    this.checkDebug();
    // app.util.request({
    //   url: 'entry/wxapp/index',
    //   module: 'cm_video_alarm',
    //   data: {
    //     op: 'sendMsgToKefu',
    //     roomID: roomInfo.roomID,
    //     roomName: roomInfo.roomInfo,
    //     userName: self.data.username
    //   },
    //   success: res => {
    //     console.log('模板消息回调',res)
    //   },
    // });

  },

  /**
     * 生命周期函数--监听页面初次渲染完成
     */
  onReady: function () {
    if (!this.versiongt(wx.systemInfo.SDKVersion, '2.7.7')) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，影响正常使用，请升级到最新微信版本后再试。',
        showCancel: false,
        success: res =>{
          wx.navigateBack({
            delta: 1,
          });
        },
      });
      return;
    }

    if (this.data.username) {
      this.init();
    } else {
      this.data.initCallback = this.init;
    }
  },

  /**
     * 生命周期函数--监听页面显示
     */
  onShow: function () {
    let self = this;
    console.log('room.js onShow');
    // 保持屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
  },

  /**
     * 生命周期函数--监听页面隐藏
     */
  onHide: function () {
    let self = this;
    console.log('room.js onHide');
  },

  /**
     * 生命周期函数--监听页面卸载
     */
  onUnload: function () {
    console.log('room.js onUnload');
  },

  /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
  onPullDownRefresh: function () {

  },

  /**
     * 页面上拉触底事件的处理函数
     */
  onReachBottom: function () {

  },

  init: function () {
    let self = this;
    // 设置房间标题
    wx.setNavigationBarTitle({
      title: self.data.roomname,
    });

    // 打印userID
    let time = new Date();
    let h = String(time.getHours());
    let m = String(time.getMinutes());
    let s = String(time.getSeconds());
    h.length == 1 ? (h = '0' + h) : '';
    m.length == 1 ? (m = '0' + m) : '';
    s.length == 1 ? (s = '0' + s) : '';
    time = h + ':' + m + ':' + s;

    let rtcroomCom = this.selectComponent('#rtcroom');
    let accountInfo = {};
    if (rtcroomCom) {
      accountInfo = rtcroom.getAccountInfo();
    }
    // accountInfo
    // {
    //     userID,			// 用户ID
    //     userName,		// 用户昵称
    //     userAvatar,		// 用户头像URL
    //     userSig,		// IM登录凭证
    //     sdkAppID,		// IM应用ID
    //     accountType,	// 账号集成类型
    //     accountMode,		//帐号模式，0-表示独立模式，1-表示托管模式
    //     token			//登录RoomService后使用的票据
    // }
    this.data.comment.push({
      content: '您当前使用的userID为' + accountInfo.userID,
      name: '【本地消息】',
      time: time,
    });
    this.setData({
      comment: this.data.comment,
      toview: '',
    });
  },

  versiongt: function(version1, version2){
    var v1 = version1.split(".");
    var v2 = version2.split(".");
    if (parseInt(v1[0]) > parseInt(v2[0])) {
      return true;
    } else if(parseInt(v1[0]) == parseInt(v2[0])) {
      if (parseInt(v1[1]) > parseInt(v2[1])) {
        return true;
      } else if(parseInt(v1[1]) == parseInt(v2[1])) {
        if (parseInt(v1[2]) >= parseInt(v2[2])) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
});
